package src.com.neusoft.nep.controller;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import src.com.neusoft.nep.common.AQI;
import src.com.neusoft.nep.common.FileUtils;
import src.com.neusoft.nep.entity.ProvidedData;

import java.util.*;

public class AQIDistributeStatisticsController {
    @FXML
    private TableView<Map<String, String>> tableView;
    @FXML
    private TableColumn<Map<String, String>, String> colAQILevel, colAQILevelDescribe, colAQILevelStatistics;

    private final ObservableList<Map<String, String>> tableList = FXCollections.observableArrayList();
    private final AQI aqiAnalyzer = new AQI();
    private Map<String, ProvidedData> dataMap; // 存储读取的数据

    public void initialize() {
        try {
            // 设置表格列值工厂
            setupTableColumns();

            // 读取数据
            dataMap = FileUtils.readMapObject("AdminData.txt");

            if (dataMap == null || dataMap.isEmpty()) {
                throw new RuntimeException("数据文件为空或读取失败");
            }

            // 分析数据并加载表格
            analyzeAndLoadData();

            // 确认表格数据
            System.out.println("表格数据内容: " + tableList);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("初始化异常: " + e.getMessage());
        }
    }

    private void setupTableColumns() {
        colAQILevel.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().get("level")));

        colAQILevelDescribe.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().get("description")));

        colAQILevelStatistics.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().get("count")));

        tableView.setItems(tableList);
    }

    private void analyzeAndLoadData() {
        tableList.clear();

        // 统计各AQI等级的数量
        Map<Integer, Integer> levelStatistics = new HashMap<>();

        // 遍历所有数据，计算AQI等级并统计
        for (ProvidedData data : dataMap.values()) {
            double so2 = Double.parseDouble(data.getSo2());
            double co = Double.parseDouble(data.getCo());
            double pm = Double.parseDouble(data.getPm());

            // 计算各污染物等级
            int so2Level = aqiAnalyzer.getLevel(so2, "so2");
            int coLevel = aqiAnalyzer.getLevel(co, "co");
            int pmLevel = aqiAnalyzer.getLevel(pm, "pm");

            // AQI等级取最大值
            int aqiLevel = Math.max(Math.max(so2Level, coLevel), pmLevel);

            // 更新统计
            levelStatistics.put(aqiLevel, levelStatistics.getOrDefault(aqiLevel, 0) + 1);
        }

        // 创建表格数据
        tableList.addAll(createAQILevelData(levelStatistics));
        System.out.println("表格数据条数: " + tableList.size());
    }

    private List<Map<String, String>> createAQILevelData(Map<Integer, Integer> statistics) {
        List<Map<String, String>> data = new ArrayList<>();

        // 定义AQI等级描述（使用LinkedHashMap保持顺序）
        Map<Integer, String> levelDescriptions = new LinkedHashMap<>();
        levelDescriptions.put(1, "优");
        levelDescriptions.put(2, "良");
        levelDescriptions.put(3, "轻度污染");
        levelDescriptions.put(4, "中度污染");
        levelDescriptions.put(5, "重度污染");
        levelDescriptions.put(6, "严重污染");

        // 确保显示所有等级，即使计数为0
        for (int level = 1; level <= 6; level++) {
            int count = statistics.getOrDefault(level, 0);

            Map<String, String> row = new HashMap<>();
            row.put("level", String.valueOf(level));
            row.put("description", levelDescriptions.get(level));
            row.put("count", String.valueOf(count));
            data.add(row);
        }

        return data;
    }
}